<template>
  <!-- <h3 style="text-align: center;">{{title}}</h3> -->
  <div>


    <div
      style=" margin-left: 50px;margin-right: 50px;border-left-style: outset;border-left-width: 2px;box-shadow: 12px 12px 12px rgba(0,0,255,0.3)">
      <el-divider></el-divider>
      <h2 v-text="tProduct.productName"></h2>

      <el-image style="width: 466px; height: 400px;float:left" :src="tProduct.productImg"></el-image>

      <div style="margin-left:999px;">
        <el-tag v-if="tAuction.status==1" type="danger">正在进行</el-tag>
        <el-tag v-else-if="tAuction.status==0" type="success">即将开始</el-tag>
        <el-tag v-else type="info">已结束</el-tag>
      </div>

      <div>
        <el-col :span="14">
          <div style="width: 50%; display: inline; ">
            <el-statistic :value="deadline" time-indices format="HH时mm分ss秒">
              <template slot="suffix"> 后结束 </template>
            </el-statistic>
          </div>
        </el-col>
      </div>

      <br>
      <div style="margin-left:735px;font-size: 16px !important">
        <h2 v-if="tAuction.status==0||tAuction.topPrice==null" v-text="'起拍价：  '+tAuction.basePrice+'元 '"></h2>
        <h2 v-else v-text="'当前价：  '+tAuction.topPrice+'元 '"></h2>
        <el-tag v-if="tAuction.status==1&&tAuction.topPrice!=null" type="danger" size="mini" closable v-text="'出价人：'+tAuction.nickname"></el-tag>
      </div>

      <br>
      <div v-if="tAuction.status<2">
        <el-form style="margin-left:715px;" :inline="true" class="demo-form-inline">
          <el-form-item label="出价">
            <el-input-number v-model="newPrice" v-if="" controls-position="right" :step="tAuction.stepPrice"
              :precision="2" step-strictly :min="startPrice"></el-input-number>
          </el-form-item>
        </el-form>
        <div style="margin-left:755px;">
          <el-button v-if="!account" type="danger" @click="toJoin()">(您未登录)报名<br>保证金￥{{tAuction.securityPrice}}
          </el-button>
          <el-button v-else-if="!join" type="danger" @click="toJoin()">报名<br>保证金￥{{tAuction.securityPrice}} </el-button>
          <el-button v-else-if="tAuction.status==0" type="info" disabled @click="toJoin()">等待开拍，开拍后出价 </el-button>
          <el-button v-else type="danger" @click="bidding()">出价 </el-button>
        </div>
      </div>
      <div v-else>
        <div style="margin-bottom: 20px;" class="title"><i class="el-icon-goblet-square-full"></i> 本场已结束！</div>
      </div>

      <br>
      <div style="margin-bottom: 5px;margin-left:720px;" class="primary"><i class="el-icon-trophy"></i> 蜗 牛 · 竞
        拍&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span v-text="tAuction.joinCount+'人参与'"></span></div>
      <br>
      <el-descriptions style="margin-left:600px;">
        <el-descriptions-item label="保证金">{{tAuction.securityPrice}}</el-descriptions-item>
        <el-descriptions-item label="起拍价">{{tAuction.basePrice}}</el-descriptions-item>
        <el-descriptions-item label="加价幅度">
          {{tAuction.stepPrice}}
        </el-descriptions-item>
        <el-descriptions-item label="竞价周期">{{tAuction.auctionTime}}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{tAuction.updateTime}}</el-descriptions-item>
      </el-descriptions>
      <h1 style="text-align:center">竞买记录</h1>

      <el-table :header-cell-style="(function (){return 'text-align:center'})"
        :cell-style="(function (){return 'text-align:center'})" :data="tAuctionItems" style="width: 100%">
        <el-table-column prop="nickname" label="竞买人" min-width="25%">
        </el-table-column>
        <el-table-column prop="auctionPrice" label="价格" min-width="25%">
        </el-table-column>
        <el-table-column prop="createTime" label="出价时间" min-width="25%">
        </el-table-column>
      </el-table>

      <div class="block" style="width:95%;text-align: center;">
        <el-pagination @current-change="initAuctionItems" :current-page.sync="currentPage" :page-size="pageSize"
          layout="prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>

    </div>

  </div>
</template>

<script>
  import Qs from "qs";
  import work5 from "./Work5";

  export default {
    name: 'Work5',
    data() {
      return {
        account: this.$cookies.get('account'),
        join: "1",
        websock: null,

        // id: '112345678923456789',
        // tProductId: '123456789123456789',
        id: this.$route.query.id,
        tProductId: this.$route.query.productId,

        pageSize: 3,
        currentPage: 1,
        tProduct: [],
        tAuction: [],
        tHistory: [],
        tAuctionItems: [],
        startPrice: "",
        newPrice: "",
        deadline: Date.now() + (new Date().setHours(23, 59, 59) - Date.now()),
        total: 0
      }
    },
    created() {
      this.initProduct();
      this.initAuction();
      this.initAuctionItems()
      if (this.account) {
        this.initIfJoin()
      }
      this.initWebSocket();
    },

    methods: {
      sendToGateway() {
        this.axios.post(
          "/moon-service-auction/auction/start",
          (res) => {}
        )
      },
      initProduct() {
        let _this = this
        let params = {
          tProductId: _this.tProductId
        }
        let data = Qs.stringify(params);
        this.axios.post("/moon-service-auction-withoutlogin/auction/queryTProduct",
          data, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).then((d) => {
          this.tProduct = d

        });
      },
      initAuctionItems() {
        let _this = this
        let params = {
          id: _this.id,
          currentPage: _this.currentPage,
          pageSize: _this.pageSize
        }
        let data = Qs.stringify(params);
        this.axios.post("/moon-service-auction-withoutlogin/auction/getItemByAuctionId",
          data, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).then((d) => {
          console.log("=================init-items====================")
          this.tAuctionItems = d.list;
          this.total = d.total;
        });
      },
      initAuction() {
        let _this = this
        let params = {
          id: _this.id
        }
        let data = Qs.stringify(params);
        this.axios.post("/moon-service-auction-withoutlogin/auction/queryTAuction",
          data, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).then((d) => {
          this.tAuction = d;
          this.startPrice = d.topPrice;
          this.newPrice = d.basePrice;
          if (d.topPrice != 0) this.newPrice = d.topPrice;

          //修改时间
          var tempTime = new Date(Date.parse(d.startTime))
          tempTime.setDate(tempTime.getDate()+1)
          this.deadline = Date.parse(tempTime)
        });
      },
      initIfJoin() {
        let _this = this
        let params = {
          id: _this.id
        }
        let data = Qs.stringify(params);
        this.axios.post("/moon-service-auction/history/queryHistory",
          data, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).then((d) => {
          this.join = d;
        });
      }

      ,
      toJoin() {
        let _this = this
        let params = {
          id: _this.id
        }
        let data = Qs.stringify(params);
        this.axios.post("/moon-service-auction/auction/join",
          data, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).then((d) => {
          this.join = d;
          alert("报名成功")
        });

      },
      bidding() {
        let _this = this
        let params = {
          id: _this.id,
          newPrice: _this.newPrice
        }
        let data = Qs.stringify(params);
        this.axios.post("/moon-service-auction/auction/bidding",
          data, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).then((d) => {
          this.$message(d)
          // _this.initAuction(),
          // _this.initAuctionItems()
        })
        this.websocketSend(this.id);
      },
      initWebSocket() {
        //初始化websocket
        let url = 'ws://127.0.0.1:8089/' + 'webSocket/' + this.id
        console.log(url)
        this.websock = new WebSocket(url);
        this.websock.onopen = this.websocketOnopen;
        this.websock.onerror = this.websocketOnerror;
        this.websock.onmessage = this.websocketOnmessage;
        this.websock.onclose = this.websocketOnclose;

      },

      //连接成功
      websocketOnopen: function() {
        console.log("WebSocket连接成功");
        //心跳检测重置
        //this.heartCheck.reset().start();
      },

      //连接错误
      websocketOnerror: function(e) {
        console.log("WebSocket连接发生错误");
        this.reconnect();
      },

      //监听后端消息
      websocketOnmessage: function(e) {
        console.log("-----接收消息-------");
        console.log(e.data);
        if(e.data == "changed"){
          console.log("刷新数据")
          this.initProduct()
          this.initAuction()
          this.initAuctionItems()
        }
        this.$alert("拍卖价格变动！")

      },

      //关闭连接
      websocketOnclose: function(e) {
        console.log("WebSocket连接关闭 (" + e.code + ")");
      },

      //向后端发送数据
      websocketSend(text) {
        try {
          this.websock.send(text);
        } catch (err) {
          console.log(err);
        }
      },

      //重新连接
      reconnect() {
        var that = this;
        if (that.lockReconnect) return;
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function() {
          console.info("尝试重连...");
          that.initWebSocket();
          that.lockReconnect = false;
        }, 5000);
      },


    },


    destroyed: function() { // 离开页面生命周期函数
      this.websock.close()
    },
  }
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
